package com.ebupt.migu.music.popup.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 开启定时任务多线程执行
 *
 * @author lemon
 * @since 2022-06-17 14:29
 */
@Configuration
@EnableAsync
public class TaskConfig {

    /**
     * 默认线程数
     */
    private static final int CORE_POOL_SIZE = 3;

    /**
     * 最大线程数
     */
    private static final int MAX_POOL_SIZE = 10;

    /**
     * 允许线程空闲时间（单位：默认为秒）,十秒后就把线程关闭
     */
    private static final int KEEP_ALIVE_TIME = 10;

    /**
     * 缓冲队列数
     */
    private static final int QUEUE_CAPACITY = 100;

    /**
     * 线程池名前缀
     */
    private static final String THREAD_NAME_PREFIX = "task-thread-";

    /**
     * bean的名称，默认为 首字小写 方法名
     *
     * @return 线程任务执行器
     */
    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor getThread() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setQueueCapacity(QUEUE_CAPACITY);
        executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        executor.setKeepAliveSeconds(KEEP_ALIVE_TIME);
        // 线程池拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}